package com.note.es.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.note.es.mapping.Hot;
import com.note.es.mapping.News;
import com.note.es.mapping.Social;
import com.note.es.service.DocumentService;
import com.note.es.utils.DocumentUtil;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DocumentServiceImpl implements DocumentService {

    @Resource
    private DocumentUtil documentUtil;

    @Override
    public boolean batchInsertNewsData(String indexName, JSONObject newsData) {
        JSONArray newsDataArray = newsData.getJSONArray("newsData");
        List<Map<String, Object>> list = new ArrayList<>();
        for (Object obj : newsDataArray) {
            JSONObject news = (JSONObject) obj;
            Map<String, Object> map = new HashMap<>();
            News.getFields().forEach(field -> {
                map.put(field, news.get(field));
            });
            list.add(map);
        }
        return documentUtil.bulkInsert(indexName, "article", list);
    }

    @Override
    public boolean batchInsertSocialData(String indexName, JSONObject socialData) {
        JSONArray socialDataArray = socialData.getJSONArray("socialData");
        List<Map<String, Object>> list = new ArrayList<>();
        for (Object obj : socialDataArray) {
            JSONObject social = (JSONObject) obj;
            Map<String, Object> map = new HashMap<>();
            Social.getFields().forEach(field -> {
                map.put(field, social.get(field));
            });
            list.add(map);
        }
        return documentUtil.bulkInsert(indexName, "social", list);
    }

    @Override
    public boolean batchInsertUserData(String indexName, JSONObject userData) {
        JSONArray userDataArray = userData.getJSONArray("hotData");
        List<Map<String, Object>> list = new ArrayList<>();
        for (Object obj : userDataArray) {
            JSONObject user = (JSONObject) obj;
            Map<String, Object> map = new HashMap<>();
            Hot.getFields().forEach(field -> {
                map.put(field, user.get(field));
            });
            list.add(map);
        }
        return documentUtil.bulkInsert(indexName, "hot", list);
    }

    @Override
    public boolean batchUpdateNewsData(String indexName, JSONObject newsData) {
        return documentUtil.bulkUpdate(indexName, "article", newsData.getJSONArray("newsData"));
    }

    @Override
    public boolean batchUpdateSocialData(String indexName, JSONObject socialData) {
        return documentUtil.bulkUpdate(indexName, "social", socialData.getJSONArray("socialData"));
    }

    @Override
    public boolean batchUpdateUserData(String indexName, JSONObject userData) {
        return documentUtil.bulkUpdate(indexName, "hot", userData.getJSONArray("hotData"));
    }
}
